<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';
import type { LineModel } from '#/api/master/models';
import type { WorkOrderModel } from '#/api/production/models';

import { onMounted, ref, watchEffect } from 'vue';

import { Page } from '@vben/common-ui';

import { Flex, InputSearch, List, ListItem, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getLineListApi } from '#/api/master/line';
import {
  getScheduleWorkOrderListApi,
  scheduleWorkOrderApi,
  sortWorkOrderApi,
} from '#/api/production/workOrder';

import { useColumns } from './data';

const searchKey = ref('');
const lineIdSelected = ref(0);
const lineData = ref<LineModel[]>([]);
const lineFilterData = ref<LineModel[]>([]);

/**
 * 排产
 * @param row
 */
function onSchedule(row: WorkOrderModel) {
  const hideLoading = message.loading({
    content: `正在排产 ${row.wo} ...`,
    duration: 0,
    key: 'action_process_msg',
  });
  scheduleWorkOrderApi(row.id)
    .then(() => {
      message.success({
        content: `${row.wo} 排产成功`,
        key: 'action_process_msg',
      });
      loadData();
    })
    .catch(() => {
      hideLoading();
    });
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<WorkOrderModel>) {
  switch (code) {
    case 'schedule': {
      onSchedule(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useColumns(onActionClick),
    border: true,
    rowConfig: {
      drag: true,
    },
    rowDragConfig: {
      showGuidesStatus: true,
      tooltipMethod({ row }) {
        return `正在移动行：${row.wo}`;
      },
      disabledMethod({ row }) {
        return !['InProgress', 'OnHold', 'Scheduled'].includes(row.status);
      },
      dragStartMethod({ row }) {
        if (!['InProgress', 'OnHold', 'Scheduled'].includes(row.status)) {
          message.warning('此单据还未排产，不允许排序');
          return false;
        }
        return true;
      },
    },
    pagerConfig: {
      enabled: false,
    },
  } as VxeGridProps<WorkOrderModel>,
  gridEvents: {
    rowDragend({ newRow, oldRow }) {
      sortWorkOrder(oldRow.id, newRow.id);
    },
  } as VxeGridListeners<WorkOrderModel>,
});

/**
 * 工单排序
 * @param fromId 源工单 Id
 * @param toId 目标工单 Id
 */
async function sortWorkOrder(fromId: number, toId: number) {
  await sortWorkOrderApi(fromId, toId);
  setTimeout(() => {
    loadData();
  }, 300);
}

/**
 * 加载数据
 */
async function loadData() {
  gridApi.setLoading(true);
  const data = await getScheduleWorkOrderListApi(lineIdSelected.value);
  gridApi.grid.loadData(data);

  setTimeout(() => {
    gridApi.setLoading(false);
  }, 300);
}

/**
 * 加载数据
 * @param lineId 产线 Id
 */
async function loadDataSource(lineId: number) {
  lineIdSelected.value = lineId;
  await loadData();
}

onMounted(async () => {
  lineData.value = await getLineListApi();
});

watchEffect(() => {
  lineFilterData.value = lineData.value.filter((s) =>
    s.lineName.includes(searchKey.value),
  );
});
</script>

<template>
  <Page auto-content-height>
    <Flex class="h-full w-full">
      <div class="h-full w-3/12">
        <List
          :data-source="lineFilterData"
          :split="false"
          bordered
          class="h-full overflow-auto"
          size="small"
        >
          <template #header>
            <div>
              <InputSearch
                v-model:value="searchKey"
                allow-clear
                placeholder="输入生产线"
                size="small"
              />
            </div>
          </template>
          <template #renderItem="{ item }">
            <ListItem>
              <div
                :class="[{ isActive: item.id === lineIdSelected }]"
                class="w-full cursor-pointer rounded-sm px-1"
                @click="loadDataSource(item.id)"
              >
                {{ item.lineName }}
              </div>
            </ListItem>
          </template>
        </List>
      </div>
      <div class="ml-2 h-full w-9/12">
        <Grid />
      </div>
    </Flex>
  </Page>
</template>

<style scoped>
.isActive {
  background-color: #1890ff;
}
</style>
